package com.kamistoat.meimeistore.commoncore.utils.file;

import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;

/**
 * 图片处理工具类
 */
public class ImageUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ImageUtils.class);

    // TODO 看这里的处理仍然是在使用后端本地存储，没有使用阿里云 OSS

    /**
     * 读取网络文件为字节数组
     *
     * @param url 地址
     * @return 字节数据
     */
    public static byte[] readFile(String url)
    {
        InputStream InputStream = null;
        try
        {
            // 网络地址
            URL urlObj = new URL(url);
            URLConnection urlConnection = urlObj.openConnection();
            urlConnection.setConnectTimeout(30 * 1000);
            urlConnection.setReadTimeout(60 * 1000);
            urlConnection.setDoInput(true);
            InputStream = urlConnection.getInputStream();
            return IOUtils.toByteArray(InputStream);
        }
        catch (Exception e)
        {
            LOGGER.error("访问文件异常 {}", e);
            return null;
        }
        finally
        {
            IOUtils.closeQuietly(InputStream);
        }
    }

    /**
     * 读取本地文件为输入流
     * @param imagePath
     * @return
     */
    public static InputStream getFile(String imagePath)
    {
        try
        {
            byte[] result = readFile(imagePath);
            result = Arrays.copyOf(result, result.length);
            return new ByteArrayInputStream(result);
        }
        catch (Exception e)
        {
            LOGGER.error("获取图片异常 {}", e);
        }
        return null;
    }

    /**
     * 根据图片路径将其转换为 byte数组
     *
     * @param imagePath
     * @return
     */
    public static byte[] getImage(String imagePath) {
        InputStream inputStream = getFile(imagePath);
        try
        {
            return IOUtils.toByteArray(inputStream);
        }
        catch (Exception e)
        {
            LOGGER.error("图片加载异常 {}", e);
            return null;
        }
        finally
        {
            IOUtils.closeQuietly(inputStream);
        }
    }
}
